package com.foodorder.controller;

import com.foodorder.dto.ApiResponse;
import com.foodorder.entity.Banner;
import com.foodorder.service.BannerService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * Banner控制器
 */
@RestController
@RequestMapping("/api/banners")
@RequiredArgsConstructor
@CrossOrigin(origins = {"http://localhost:3001", "http://localhost:3002"})
public class BannerController {
    
    private final BannerService bannerService;
    
    /**
     * 获取前端展示的Banner列表
     */
    @GetMapping("/active")
    public ApiResponse<List<Banner>> getActiveBanners() {
        try {
            List<Banner> banners = bannerService.getActiveBanners();
            return ApiResponse.success(banners);
        } catch (Exception e) {
            return ApiResponse.error("获取Banner列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 管理端分页查询Banner
     */
    @GetMapping
    public ApiResponse<Map<String, Object>> getBanners(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String status) {
        try {
            Pageable pageable = PageRequest.of(page - 1, size);
            Banner.BannerStatus bannerStatus = null;
            if (status != null && !status.isEmpty()) {
                bannerStatus = Banner.BannerStatus.valueOf(status.toUpperCase());
            }
            
            Page<Banner> bannerPage = bannerService.findBanners(title, bannerStatus, pageable);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", bannerPage.getContent());
            result.put("total", bannerPage.getTotalElements());
            result.put("page", page);
            result.put("size", size);
            result.put("totalPages", bannerPage.getTotalPages());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("查询Banner失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取Banner详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Banner> getBannerById(@PathVariable Long id) {
        try {
            return bannerService.findById(id)
                    .map(ApiResponse::success)
                    .orElse(ApiResponse.error("Banner不存在"));
        } catch (Exception e) {
            return ApiResponse.error("获取Banner失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加Banner
     */
    @PostMapping
    public ApiResponse<Banner> createBanner(@RequestBody Banner banner) {
        try {
            Banner savedBanner = bannerService.save(banner);
            return ApiResponse.success(savedBanner);
        } catch (Exception e) {
            return ApiResponse.error("添加Banner失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新Banner
     */
    @PutMapping("/{id}")
    public ApiResponse<Banner> updateBanner(@PathVariable Long id, @RequestBody Banner banner) {
        try {
            if (!bannerService.findById(id).isPresent()) {
                return ApiResponse.error("Banner不存在");
            }
            banner.setId(id);
            Banner savedBanner = bannerService.save(banner);
            return ApiResponse.success(savedBanner);
        } catch (Exception e) {
            return ApiResponse.error("更新Banner失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除Banner
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteBanner(@PathVariable Long id) {
        try {
            if (!bannerService.findById(id).isPresent()) {
                return ApiResponse.error("Banner不存在");
            }
            bannerService.deleteById(id);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("删除Banner失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量删除Banner
     */
    @DeleteMapping("/batch")
    public ApiResponse<Void> deleteBanners(@RequestBody List<Long> ids) {
        try {
            bannerService.deleteByIds(ids);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("批量删除Banner失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新Banner状态
     */
    @PutMapping("/{id}/status")
    public ApiResponse<Void> updateBannerStatus(@PathVariable Long id, @RequestParam String status) {
        try {
            Banner.BannerStatus bannerStatus = Banner.BannerStatus.valueOf(status.toUpperCase());
            bannerService.updateStatus(id, bannerStatus);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("更新Banner状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新排序
     */
    @PutMapping("/{id}/sort")
    public ApiResponse<Void> updateSortOrder(@PathVariable Long id, @RequestParam Integer sortOrder) {
        try {
            bannerService.updateSortOrder(id, sortOrder);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("更新排序失败: " + e.getMessage());
        }
    }
} 